package br.com.mmca.admrespaco.business;


import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import br.gov.frameworkdemoiselle.message.MessageContext;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.frameworkdemoiselle.template.DelegateCrud;
import br.gov.frameworkdemoiselle.transaction.Transactional;

import br.com.mmca.admrespaco.domain.Reserva;
import br.com.mmca.admrespaco.persistence.ReservaDAO;

import br.com.mmca.admrespaco.message.InfoMessages;
import br.com.mmca.admrespaco.message.ErrorMessages;

@BusinessController
public class ReservaBC extends DelegateCrud<Reserva, Long, ReservaDAO> {
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private EspacoBC espacoBC;
	
	@Inject
	private CondominoBC condominoBC;
	
	private boolean erro;
	
    @Inject
	private MessageContext msg;
	
		
	@Override
	@Transactional
	public void insert(final Reserva se) {
		validateFields(se);
		if (! erro) {
		  super.insert(se);
		  msg.add(InfoMessages.reserva_insert_ok, se.getId());
		}
		
	}
	@Override
	@Transactional
	public void update(final Reserva se) {
		validateFields(se);
		if (! erro) {
		  super.update(se);
		  msg.add(InfoMessages.reserva_update_ok, se.getId());
		}
		
	}
	
	@Override
	@Transactional
	public void delete(final Long id) {
		super.delete(id);
		 msg.add(InfoMessages.reserva_delete_ok, id);
		 
	}
	
	
	@SuppressWarnings("unused")
	private void validateFields(final Reserva se) 
	{
		
		erro=false;
		
		if (espacoBC.load(se.getIdEspaco())== null) // Se Espaco existe
		{
		    erro=true;
			msg.add(ErrorMessages.reserva_idespaco_nok, se.getIdEspaco());
			return;
		}
		if (condominoBC.load(se.getIdCondomino())== null)  // Se Condomino existe
		{
		    erro=true;
			msg.add(ErrorMessages.reserva_idcondomino_nok, se.getIdCondomino());
			return;
		}
		
		try        // Se data eh valida
		{
		  Date dt = null;
		  SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
		  dt = formato.parse(se.getDataReserva());
		}
		catch (ParseException e)
		{
			erro=true;
			msg.add(ErrorMessages.reserva_data_nok, se.getDataReserva());
			return;
		}
		// Se a reserva ja exite para o espaco
		List<Reserva> lista = super.getDelegate().findByEspaco(se.getIdEspaco());
		for (Reserva m : lista)
		{
			if (m.getDataReserva().equalsIgnoreCase(se.getDataReserva()))
			{
				erro=true;
				msg.add(ErrorMessages.reserva_existe, se.getIdEspaco(), se.getDataReserva());
				return;
			}
		}
		
	}
	
}
